<template>
	<view>
	<u-popup
		mode="bottom"
		closeable
		zIndex="9"
		:show="showConpon"
		@close="closeConpon">
		<view class="coupon-popup coupon-popup1">
			<view class="coupon-popup-title main-flex">选择优惠券</view>
			<view class="coupon-popup-tabs main-flex">
				<u-tabs
					lineColor="#e3230e"
					lineWidth="90rpx"
					:itemStyle="{
						height: '36px',
						fontSize: '32rpx',
						padding: '0 80rpx'
					}"
					:inactiveStyle="{
						color: '#333333'
					}"
					:activeStyle="{
						color: '#e3230e',
						fontWeight: '600'
					}"
					:scrollable="false"
					:list="tabList"
					 :current="current"
					@click="clickTab"></u-tabs>
			</view>
			<view class="coupon-popup-content" @touchmove.stop.prevent>
				<swiper class="coupon-popup-swiper" :current="current" @change="changeSwiper">
					<swiper-item>
						<view class="coupon-popup-swiper-item">
							<scroll-view class="coupon-list" scroll-y>
								<view class="coupon-list-box">
									<view class="coupon-list-item" v-for="item in tableList1" :key="item.id">
										<coupon-item :coupon="item">
											<template #radio="{item1}">
												<view class="coupon-item-choose main-flex">
													<view class="coupon-item-choose-box" @click="changeCoupon(item)">
														<uni-icons v-if="chooseCouponList.indexOf(item.id) > -1" type="checkbox-filled" size="24" color="#e3230e"></uni-icons>
														<uni-icons v-else type="circle" size="24" color="#c8c9cc"></uni-icons>
													</view>
												</view>
											</template>
										</coupon-item>
									</view>
									<view
										v-if="isNull1"
										class="null main-flex">
										<u-empty text="暂无优惠券" icon="/static/images/null.png"></u-empty>
										<view class="null-btn" @click="goUrl('/pages/coupon/list')">去领券</view>
									</view>
								</view>
							</scroll-view>
						</view>
					</swiper-item>
					<swiper-item>
						<view class="coupon-popup-swiper-item">
							<scroll-view class="coupon-list" scroll-y>
								<view class="coupon-list-box">
									<view class="coupon-list-item" v-for="item in tableList2" :key="item.id">
										<coupon-item :coupon="item">
											<template #radio="{item1}">
												<view class="coupon-item-choose main-flex">
													<view class="coupon-item-choose-box" @click="changeCouponProduct(item)">
														<uni-icons v-if="chooseCouponProductList.indexOf(item.id) > -1" type="checkbox-filled" size="24" color="#e3230e"></uni-icons>
														<uni-icons v-else type="circle" size="24" color="#c8c9cc"></uni-icons>
													</view>
												</view>
											</template>
										</coupon-item>
									</view>
									<view
										v-if="isNull2"
										class="null main-flex">
										<u-empty text="暂无优惠券" icon="/static/images/null.png"></u-empty>
										<view class="null-btn" @click="goUrl('/pages/coupon/list')">去领券</view>
									</view>
								</view>
							</scroll-view>
						</view>
					</swiper-item>
				</swiper>
			</view>
			<view class="coupon-popup-footer main-flex">
				<view class="coupon-popup-money">
					<text>共计优惠</text>
					<text class="coupon-popup-money-unit">￥</text>
					<text class="coupon-popup-money-num">{{couponMoney ? moneyStr(couponMoney) : '0.00'}}</text>
				</view>
				<button class="ty-button ty-button-confirm coupon-popup-btn" @click="confirmCoupon">确认</button>
			</view>
		</view>
	</u-popup>
	</view>
</template>

<script setup>
  /**
   * ChooseConpon 选择优惠券
   * @description 选择优惠券
   * @event {Function} close 关闭
   * @event {Function} confirm 确认
   */
	import { computed, onMounted, ref, watch, watchEffect, nextTick } from "vue"
	import useUserStore from "@/store/modules/user"
	import useSetStore from '@/store/modules/set'
	import modal from '@/plugins/modal'
	import { arrText } from "@/utils/ty"
	import { couponSelf } from "@/api/app_api/user"
	import { availableCouponProdtuct } from "@/api/app_api/coupon"
	
	const userStore = useUserStore()
	const setStore = useSetStore()
	const props = defineProps({
		showConpon: {
			type: Boolean,
			default: false 
		},
		productList: {
			type: Array,
			default: []
		},
		couponList: {
			type: Array,
			default: []
		},
		couponProductList: {
			type: Array,
			default: []
		},
		total: {
			type: Object,
			default: {}
		}
	})
	
	const emits = defineEmits(['close', 'change', 'confirm'])
	const closeConpon = () => {
		emits('close', false)
	}
	
	const tabList = ref([
		{ type: 0, name: '通用券' },
		{ type: 1, name: '商品券' }
	])
	const type = ref(0)
	const current = ref(0)
	const clickTab = (e) => {
		current.value = e.index
		type.value = e.type
	}
	const changeSwiper = (e) => {
		current.value = e.detail.current
	}
	
	// 列表查询
	const tableList1 = ref([])
	const isNull1 = ref(false)
	
	const getList = () => {
		couponSelf({
			status: 0
		}).then((res) => {
			tableList1.value = res.data.map(item => {
				return {
					...item,
					disabled: props.total?.originalPrice ? parseFloat(props.total?.originalPrice) < parseFloat(item?.coupon?.minConsume) : true
				}
			})
			isNull1.value = tableList1.value.length === 0
		}).catch(() => {
			isNull1.value = false
		})
	}
	
	const tableList2 = ref([])
	const isNull2 = ref(false)
	
	const getList2 = () => {
		availableCouponProdtuct(props.productList || []).then((res) => {
			tableList2.value = res.data.map(item => {
				let disabled = false
				if (item.type == 8) { // 组合
					const productFilter = props.productList.filter(goods => goods?.typeId == item?.couponProduct?.productId)
					// console.log(productFilter)
					disabled = productFilter.length < item?.couponProduct?.leastNumber
				} else {
					const productFilter = props.productList.filter(goods => goods.productId == item?.couponProduct?.productId)
					// console.log(productFilter)
					disabled = productFilter.length > 0 ? productFilter[0].number < item?.couponProduct?.leastNumber : true
				}
				return {
					...item,
					disabled
				}
			})
			isNull2.value = tableList2.value.length === 0
		}).catch(() => {
			isNull2.value = false
		})
	}
	
	const goUrl = (url) => {
		uni.navigateTo({
			url
		})
		emits('close', false)
	}
	
	// 选择优惠券
	const chooseCoupon = ref([])
	const chooseCouponList = ref([])
	// 满减券
	const changeCoupon = (item) => {
		if (item.disabled) return false
		const chooseCouponFilter = chooseCouponList.value.filter(i => i == item.id)
		if (chooseCouponFilter.length === 0) {
			if (!isAccumulationFlag1(item.id)) { // 不可叠加
				chooseCouponList.value = chooseCouponList.value.filter(i => isAccumulationFlag1(i))
			}
			chooseCouponList.value.push(item.id)
		} else {
			chooseCouponList.value = chooseCouponList.value.filter(i => i != item.id)
		}
		emitChangeCoupon()
	}
	// 商品券
	const chooseCouponProductList = ref([])
	const changeCouponProduct = (item) => {
		if (item.disabled) return false
		const chooseCouponProductFilter = chooseCouponProductList.value.filter(i => i == item.id)
		if (chooseCouponProductFilter.length === 0) {
			if (!isAccumulationFlag2(item.id)) { // 不可叠加
				chooseCouponProductList.value = chooseCouponProductList.value.filter(i => isAccumulationFlag2(i))
			}
			chooseCouponProductList.value.push(item.id)
		} else {
			chooseCouponProductList.value = chooseCouponProductList.value.filter(i => i != item.id)
		}
		emitChangeCoupon()
	}
	
	// 确认选择
	const emitChangeCoupon = () => {
		const chooseCouponIdList = tableList1.value.filter(i => chooseCouponList.value.indexOf(i.id) > -1)
		const chooseCouponProductIdList = tableList2.value.filter(i => chooseCouponProductList.value.indexOf(i.id) > -1)
		emits('change', {
			couponList: chooseCouponIdList.map(item => {
				return {
					ad: item?.coupon?.ad || '',
					couponName: item.couponName,
					couponId: item.couponId,
					couponRecordId: item.id
				}
			}),
			couponProductList: chooseCouponProductIdList.map(item => {
				return {
					ad: item?.couponProduct?.ad || '',
					couponProductName: item.couponProductName,
					couponProductId: item.couponProductId,
					couponProductRecordId: item.id
				}
			})
		})
	}
	
	// 确认优惠券
	const confirmCoupon = () => {
		const chooseCouponIdList = tableList1.value.filter(i => chooseCouponList.value.indexOf(i.id) > -1)
		const chooseCouponProductIdList = tableList2.value.filter(i => chooseCouponProductList.value.indexOf(i.id) > -1)
		emits('confirm', {
			couponList: chooseCouponIdList.map(item => {
				return {
					ad: item?.coupon?.ad || '',
					couponName: item.couponName,
					couponId: item.couponId,
					couponRecordId: item.id
				}
			}),
			couponProductList: chooseCouponProductIdList.map(item => {
				return {
					ad: item?.couponProduct?.ad || '',
					couponProductName: item.couponProductName,
					couponProductId: item.couponProductId,
					couponProductRecordId: item.id
				}
			})
		})
		emits('close')
	}
	
	// 判断当前优惠券是否可叠加
	const isAccumulationFlag1 = (id) => {
		const filter1 = tableList1.value.find(item => item.id == id && item?.coupon?.accumulationFlag === 1)
		return filter1 ? true : false
	}
	// 判断当前商品券是否可叠加
	const isAccumulationFlag2 = (id) => {
		const filter2 = tableList2.value.find(item => item.id == id)
		return filter2 ? true : false
	}
	
	const couponMoney = computed(() => {
		const money1 = tableList1.value.filter(i => chooseCouponList.value.indexOf(i.id) > -1).reduce((prev, cur, index, arr)=> {
				return prev + cur.coupon.discountMoney
			}, 0)
		const money2 = tableList2.value.filter(i => chooseCouponProductList.value.indexOf(i.id) > -1).reduce((prev, cur, index, arr)=> {
				return prev + cur.couponProduct.discountPrice
			}, 0)
		return money1 + money2
	})
	
	// watchEffect(() => {
	// 	console.log(props)
	// 	// chooseCouponList.value = props.couponList.map(item => item.couponRecordId)
	// 	// chooseCouponProductList.value = props.couponProductList.map(item => item.couponProductRecordId)
	// })
	
	watch(() => props.showConpon, (nval, oval) => {
		if (nval) {
			getList()
			getList2()
			chooseCouponList.value = props.couponList.map(item => item.couponRecordId)
			chooseCouponProductList.value = props.couponProductList.map(item => item.couponProductRecordId)
		}
	})
</script>

<style lang="scss" scoped>
  .coupon-popup {
		border-radius: 20rpx 20rpx 0rpx 0rpx;
		background-color: #ffffff;
		&-title {
			height: 48px;
			font-size: 16px;
			font-weight: 600;
			text-align: center;
			justify-content: center;
			padding: 0 30rpx;
		}
		&-tabs {
			justify-content: center;
		}
		&-content {
			background-color: #f5f5f5;
		}
		&-swiper {
			height: 680rpx;
		}
		.coupon{
			&-list {
				height: 680rpx;
				padding: 0 15px;
				box-sizing: border-box;
				&-box {
					padding: 20rpx 0;
				}
				.coupon-list-item + .coupon-list-item {
					margin-top: 20rpx;
				}
			}
			&-item {
				&-choose {
					padding-left: 20rpx;
				}
			}
		}
		&-footer {
			padding: 20rpx;
		}
		&-money {
			font-size: 28rpx;
			&-unit {
				color: $primary-color;
			}
			&-num {
				font-size: 36rpx;
				color: $primary-color;
			}
		}
		&-btn {
			width: 160rpx;
			height: 68rpx;
			border-radius: 34rpx;
			font-size: 28rpx;
			margin-left: auto;
		}
	}
	.coupon-popup1 {
		padding-bottom: 0rpx;
	}
</style>
